package com.infore.airsupervise.ui.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.infore.airsupervise.R;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.LoginBiz;
import com.infore.airsupervise.biz.impl.LoginBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LocalInfo;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 站点视频
 */
public class StationVideoActivity extends BaseTitleBarActivity implements Handler.Callback, SurfaceHolder.Callback {
    @BindView(R.id.btn_video_up)
    Button btnVideoUp;
    @BindView(R.id.btn_video_down)
    Button btnVideoDown;
    @BindView(R.id.btn_video_left)
    Button btnVideoLeft;
    @BindView(R.id.btn_video_right)
    Button btnVideoRight;
    @BindView(R.id.iv_video_bg)//控制方向的背景图片
            ImageView ivVideoBg;
    @BindView(R.id.sv_real_play)
    SurfaceView svRealPlay;
    @BindView(R.id.layout_progress)
    LinearLayout layoutProgress;
    @BindView(R.id.tv_discrib)
    TextView tvReload;
    @BindView(R.id.ll_video_reload)
    LinearLayout llVideoReload;
    @BindView(R.id.ll_video_load)
    FrameLayout llVideoLoad;
    private ImageView iv_play;//播放暂停

    private EZDeviceInfo deviceInfo;

    private Handler myHandler;

    private EZPlayer mEZPlayer;                 // 播放器
    private EZCameraInfo mCameraInfo;           // 摄像头对象
    private LocalInfo mLocalInfo;

    private Handler mHandler = null;                    // 处理播放器发出的消息
    private SurfaceHolder mRealPlaySh = null;           // SurfaceView持有
    /**
     * 标识是否正在播放
     */
    private int mStatus = RealPlayStatus.STATUS_INIT;
    private boolean mIsOnStop = false;
    private boolean isFirst = true;
    private String deviceSerial; //设备编号
    private GetDeviceInfoTask getDeviceInfoTask;

    private LoginBiz getTokenBiz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_station_video);
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ButterKnife.bind(this);
        //设置token

        if (TextUtils.isEmpty(UserE.getVideoToken())) {
            getToken();
        } else {
            setToken();
        }
        initView();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        //titleBar 设置
        title.setText("实时视频");
        rightMenu.setVisibility(View.INVISIBLE);

        btnVideoDown.setOnTouchListener(mOnTouchListener);
        btnVideoLeft.setOnTouchListener(mOnTouchListener);
        btnVideoRight.setOnTouchListener(mOnTouchListener);
        btnVideoUp.setOnTouchListener(mOnTouchListener);
        setOptionBtnEnble(false);
        // 获取配置信息操作对象
        mLocalInfo = LocalInfo.getInstance();
        mLocalInfo.setSoundOpen(false);
        // 实例接收播放器消息的Handler
        mHandler = new Handler(this);
        mRealPlaySh = svRealPlay.getHolder();
        mRealPlaySh.addCallback(this);
        // iv_play.setVisibility(View.GONE);
    }

    /**
     * 开始播放
     *
     * @see
     * @since V2.0
     */
    private void startRealPlay() {
        if (mStatus == RealPlayStatus.STATUS_START || mStatus == RealPlayStatus.STATUS_PLAY) {
            return;
        }
        // 检查网络是否可用
        if (!ConnectionDetector.isNetworkAvailable(this)) {
            // 提示没有连接网络
          loadFailedUI("网络异常，请检查你的网络设置！");
            return;
        }
        mStatus = RealPlayStatus.STATUS_START;
        if (mCameraInfo != null) {
            if (mEZPlayer == null) {
                mEZPlayer = EZOpenSDK.getInstance().
                        createPlayer(mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo());
            }
            if (mEZPlayer == null)
                return;
            if (deviceInfo == null) {
                return;
            }
            mEZPlayer.setHandler(mHandler);
            mEZPlayer.setSurfaceHold(mRealPlaySh);
            mEZPlayer.startRealPlay();
        }
    }

    /**
     * 停止播放
     *
     * @see
     * @since V1.0
     */
    private void stopRealPlay() {
        mStatus = RealPlayStatus.STATUS_STOP;
        if (mEZPlayer != null) {
            mEZPlayer.stopRealPlay();
        }
    }


    /**
     * 云台控制按钮 是否可用
     */

    private void setOptionBtnEnble(boolean isEnbled) {
        btnVideoUp.setEnabled(isEnbled);
        btnVideoRight.setEnabled(isEnbled);
        btnVideoLeft.setEnabled(isEnbled);
        btnVideoDown.setEnabled(isEnbled);
    }

    /**
     * 设置音频播放
     */
    private void setRealPlaySound() {
        if (mEZPlayer != null) {
            if (mLocalInfo.isSoundOpen()) {
                mEZPlayer.openSound();
            } else {
                mEZPlayer.closeSound();
            }
        }
    }

    /**
     * 云台操作
     *
     * @param command ptz控制命令
     * @param action  控制启动/停止
     */
    private void ptzOption(final EZConstants.EZPTZCommand command, final EZConstants.EZPTZAction action) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean ptz_result = false;
                try {
                    ptz_result = EZOpenSDK.getInstance().controlPTZ(mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo(), command,
                            action, EZConstants.PTZ_SPEED_DEFAULT);
                } catch (BaseException e) {
                    e.printStackTrace();
                }
                Log.i("test", "controlPTZ ptzCtrl result: " + ptz_result);
            }
        }).start();
    }

    /**
     * 触碰事件（四个方向按钮）
     */
    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            int action = motionEvent.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    switch (view.getId()) {
                        case R.id.btn_video_up:
                            ivVideoBg.setImageResource(R.drawable.paly_button_top);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.btn_video_down:
                            ivVideoBg.setImageResource(R.drawable.paly_button_bottom);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.btn_video_left:
                            ivVideoBg.setImageResource(R.drawable.paly_button_left);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.btn_video_right:
                            ivVideoBg.setImageResource(R.drawable.paly_button_right);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    ivVideoBg.setImageResource(R.drawable.paly_button);
                    switch (view.getId()) {
                        case R.id.btn_video_up:
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.btn_video_down:
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.btn_video_left:
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.btn_video_right:
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                handlePlaySuccess(message);
                break;
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                handlePlayFail(message.obj);
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        if (mEZPlayer != null) {
            mEZPlayer.setSurfaceHold(surfaceHolder);
        }
        mRealPlaySh = surfaceHolder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        if (mEZPlayer != null) {
            mEZPlayer.setSurfaceHold(null);
        }
        mRealPlaySh = null;
    }

    /**
     * 处理播放成功的情况
     *
     * @see
     * @since V1.0
     */
    private void handlePlaySuccess(Message msg) {
        mStatus = RealPlayStatus.STATUS_PLAY;
        loadSuccessUI();
        // 声音处理

        //开启云带控制键
        setOptionBtnEnble(true);
    }

    /**
     * 处理播放失败的情况
     *
     * @param obj - 错误码
     * @see
     * @since V1.0
     */
    private void handlePlayFail(Object obj) {
        String errorDetai = "";
        if (obj != null) {
            ErrorInfo errorInfo = (ErrorInfo) obj;
            errorDetai = errorInfo.description;
        }
        loadFailedUI(errorDetai);
        setOptionBtnEnble(false);
        stopRealPlay();
    }

    /**
     * 播放周期同步activity生命周期
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst) {
            if (mCameraInfo != null && deviceInfo != null && deviceInfo.getStatus() != 1) {
                if (mStatus != RealPlayStatus.STATUS_STOP) {
                    stopRealPlay();
                }
            } else {
                if (mStatus == RealPlayStatus.STATUS_INIT || mStatus == RealPlayStatus.STATUS_PAUSE
                        || mStatus == RealPlayStatus.STATUS_DECRYPT) {
                    // 开始播放
                    loadingResetUI();
                    startRealPlay();

                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCameraInfo == null) {
            return;
        }
        if (mStatus != RealPlayStatus.STATUS_STOP) {
            mIsOnStop = true;
            stopRealPlay();
            mStatus = RealPlayStatus.STATUS_PAUSE;
        } else {
            llVideoLoad.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEZPlayer != null) {
            mEZPlayer.release();
        }
        mHandler = null;
        if (null != getDeviceInfoTask && getDeviceInfoTask.getStatus().equals(AsyncTask.Status.RUNNING)) {
            getDeviceInfoTask.cancel(true);
        }
    }



    /**
     * 子线程 异步获取设备对象
     */

    private class GetDeviceInfoTask extends AsyncTask<Void, Void, EZDeviceInfo> {

        @Override
        protected EZDeviceInfo doInBackground(Void... voids) {
            try {
                //根据设备编码获取对应设备对象
                EZDeviceInfo result = EZOpenSDK.getInstance().getDeviceInfo("672265207");
                return result;
            } catch (final BaseException e) {
                //异常 获取播放设备失败处理
                final ErrorInfo errorInfo = (ErrorInfo) e.getObject();
                if (errorInfo.errorCode == 110002 || errorInfo.errorCode == 110003 ||errorInfo.errorCode == 110001) {//token 过期 或错误
                    if (getDeviceInfoTask.getStatus().equals(Status.RUNNING)) {
                        getDeviceInfoTask.cancel(true);
                    }
                    getToken();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadFailedUI(errorInfo.description);
                        }
                    });
                }
                return null;
            }
        }

        @Override
        protected void onPostExecute(EZDeviceInfo ezDeviceInfo) {
            super.onPostExecute(ezDeviceInfo);
            if (ezDeviceInfo == null) {
                return;
            }
            deviceInfo = ezDeviceInfo;
            List<EZCameraInfo> cameraInfos = deviceInfo.getCameraInfoList();
            if (cameraInfos != null && cameraInfos.size() > 0) {
                // 测试用：仅一个摄像头时的处理
                mCameraInfo = cameraInfos.get(0);
                isFirst = false;
                startRealPlay();
            }
        }
    }

    /**
     * 获取token
     */
    private void getToken() {
        if (null == getTokenBiz) {
            getTokenBiz = new LoginBizImpl();
        }
        getTokenBiz.getVideoTokenReuqest(new OnServerResponseListener<String>() {
            @Override
            public void onSucceed(String result, String desc) {
                UserE.saveToken(result);
                setToken();
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                loadFailedUI(desc);
            }
        });
    }

    private void setToken() {
        EZOpenSDK.getInstance().setAccessToken(UserE.getVideoToken());
        getDeviceInfoTask = new GetDeviceInfoTask(); //异步处理 获取视频设备对象
        getDeviceInfoTask.execute();

    }


    private void loadFailedUI(String detail) {
        llVideoLoad.setVisibility(View.VISIBLE);
        llVideoReload.setVisibility(View.VISIBLE);
        layoutProgress.setVisibility(View.GONE);
        tvReload.setText(detail);
    }

    private void loadSuccessUI() {
        llVideoLoad.setVisibility(View.GONE);
    }

    private void loadingResetUI() {
        llVideoLoad.setVisibility(View.VISIBLE);
        llVideoReload.setVisibility(View.GONE);
        layoutProgress.setVisibility(View.VISIBLE);
    }
    @OnClick(R.id.tv_reload)
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_reload:
            if(mStatus!= RealPlayStatus.STATUS_STOP){
                stopRealPlay();
            }else {
                loadingResetUI();
                if(null == deviceInfo){
                    setToken();
                }else {
                    startRealPlay();
                }
            }
            break;
        }
    }
}
